<template>
  <div class="uers_wrapper">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="handelSearchClear"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handelSearchClick(queryInfo.query)"
            ></el-button></el-input
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handelAddUserClick"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userList" :stripe="true" :border="true">
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="email" label="邮箱" align="center">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" align="center">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" align="center">
        </el-table-column>
        <el-table-column label="状态" width="150" align="center">
          <template v-slot:default="slotProps">
            <el-switch
              v-model="slotProps.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handelSwitchchange(slotProps.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template v-slot:default="slotProps">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handelEditClick(slotProps.row.id)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-delete"
              size="mini"
              @click="removeIdClick(slotProps.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.pagenum"
        :page-sizes="[1, 5, 8, 10]"
        :page-size="queryInfo.pagesize"
        layout="total,sizes, prev, pager, next ,jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="handelAddColseDialog"
    >
      <el-form
        :model="AddForm"
        :rules="AddFormRules"
        ref="AddFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="AddForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="AddForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="AddForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="AddForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handelAddColseDialog">取 消</el-button>
        <el-button type="primary" @click="addUserClick">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击编辑的对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @colse="handelEditColse"
    >
      <el-form
        :model="EditForm"
        :rules="EditFormRules"
        ref="EditFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="EditForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="EditForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="EditForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handelEditColse">取 消</el-button>
        <el-button type="primary" @click="handelEditSubmitClick(EditForm.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  GetUserList,
  changeUserList,
  AddUser,
  Getuser,
  EditUerInfo,
  DeleteUserInfo
} from '../../request/api.js'
export default {
  name: 'Users',
  data() {
    // 校验邮箱自定义规则
    const CheckEmail = (rules, value, cb) => {
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regEmail.test(value)) return cb()
      cb(new Error('请输入合法的邮箱'))
    }
    // 校验手机号的规则
    const CheckMoblie = (rules, value, cb) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (regMobile.test(value)) return cb()
      cb(new Error('请输入合法的手机号'))
    }

    return {
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示的个数
        pagesize: 1
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      AddForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      AddFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '用户名长度在3-5个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在6-16个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: CheckEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: CheckMoblie, trigger: 'blur' }
        ]
      },
      EditForm: {
        username: '',
        mobile: '',
        email: ''
      },
      EditFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: CheckEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: CheckMoblie, trigger: 'blur' }
        ]
      },
      editDialogVisible: false
    }
  },
  created() {
    this.GetUserList()
  },
  methods: {
    // 获取用户列表的函数
    async GetUserList() {
      const { data: res } = await GetUserList(this.queryInfo)
      const { data, meta } = res
      if (!meta.status === 200) {
        return this.$message(meta.msg)
      }
      this.userList = data.users
      this.total = data.total
    },
    // 每页的条数改变的时候触发
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.GetUserList()
    },
    // 页面值改变的时候触发
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.GetUserList()
    },
    // 点击切换switch的时候
    async handelSwitchchange(val) {
      try {
        const { data: res } = await changeUserList(val.id, val.mg_state)
        if (res.meta.status !== 200) {
          this.userList.mg_state = !this.userList.mg_state
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 点击根据名字查询
    handelSearchClick(val) {
      this.GetUserList()
    },
    // 点击清空
    handelSearchClear() {
      this.GetUserList()
    },
    // 点击添加用户显示对话框
    handelAddUserClick() {
      this.addDialogVisible = !this.addDialogVisible
    },
    // 关闭对话框的事件
    handelAddColseDialog() {
      this.addDialogVisible = false
      this.$refs.AddFormRef.clearValidate()
      this.$refs.AddFormRef.resetFields()
    },
    // 点击确认按钮，添加新用户
    addUserClick() {
      this.$refs.AddFormRef.validate(async (valid, strobj) => {
        if (!valid) return false
        try {
          const { data } = await AddUser(this.AddForm)
          if (!data.meta.status === 201) {
            return this.$message.error(data.meta.msg)
          }
          this.$message.success(data.meta.msg)
          this.addDialogVisible = false
        } catch (error) {
          this.$message.error(error)
        }
      })
    },
    // 点击展示编辑对话框
    async handelEditClick(id) {
      this.editDialogVisible = true
      try {
        const { data } = await Getuser(id)
        if (!data.meta.status === 200) return this.$message.error(data.meta.msg)
        this.EditForm = data.data
        console.log(data)
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 编辑表单的取消
    handelEditColse() {
      this.$refs.EditFormRef.resetFields()
      this.$refs.EditFormRef.clearValidate()
      this.editDialogVisible = false
    },
    // 编辑对话框点击确认提交
    handelEditSubmitClick(id) {
      this.$refs.EditFormRef.validate(async valid => {
        if (!valid) return false
        const params = {
          email: this.EditForm.email,
          mobile: this.EditForm.mobile
        }
        const { data } = await EditUerInfo(id, params)
        if (!data.meta.status === 200) {
          return this.$message.error(data.meta.msg)
        }
        this.$message.success(data.meta.msg)
        this.editDialogVisible = false
        this.GetUserList()
      })
    },
    // 根据id删除用户
    removeIdClick(id) {
      this.$confirm('此操作将永久删除用户 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          DeleteUserInfo(id)
            .then(res => {
              if (!res.data.meta.status === 200) {
                return this.$message({
                  type: 'info',
                  message: 'res.data.meta.msg'
                })
              }
              this.GetUserList()
              return this.$message.success(res.data.meta.msg)
            })
            .catch(error => {
              return this.$message.error(error)
            })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() =>
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        )
    }
  }
}
</script>

<style lang="less" scoped></style>
